package com.wanwanbookstore.servlet;

import com.wanwanbookstore.dao.OrderDAO;
import com.wanwanbookstore.entity.Order;
import com.wanwanbookstore.entity.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class OrderServlet extends HttpServlet {
    private OrderDAO orderDAO = new OrderDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        String action = request.getParameter("action");
        if (action == null) action = "list";

        switch (action) {
            case "list":
                listOrders(request, response, user);
                break;
            case "detail":
                orderDetail(request, response, user);
                break;
            case "success":
                orderSuccess(request, response);
                break;
            default:
                listOrders(request, response, user);
        }
    }

    private void listOrders(HttpServletRequest request, HttpServletResponse response, User user) throws ServletException, IOException {
        List<Order> orders = orderDAO.getOrdersByUserId(user.getId());
        request.setAttribute("orders", orders);
        request.getRequestDispatcher("order_list.jsp").forward(request, response);
    }

    private void orderDetail(HttpServletRequest request, HttpServletResponse response, User user) throws ServletException, IOException {
        String orderId = request.getParameter("id");
        Order order = orderDAO.getOrderById(orderId);

        // 检查订单是否属于当前用户
        if (order != null && order.getUserId() == user.getId()) {
            request.setAttribute("order", order);
            request.getRequestDispatcher("order_detail.jsp").forward(request, response);
        } else {
            response.sendRedirect("order?action=list");
        }
    }

    private void orderSuccess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String orderId = request.getParameter("id");
        // 获取订单信息以获取总金额
        Order order = orderDAO.getOrderById(orderId);
        double totalPrice = 0;
        if (order != null) {
            totalPrice = order.getTotalPrice();
        }
        
        request.setAttribute("orderId", orderId);
        request.setAttribute("totalPrice", totalPrice);
        request.getRequestDispatcher("order_success.jsp").forward(request, response);
    }
}